package com.xinxin.websocket.server;

import com.google.gson.Gson;
import com.xinxin.websocket.dataobject.Message;
import com.xinxin.websocket.dataobject.User;
import com.xinxin.websocket.service.UserService;
import com.xinxin.websocket.utils.MessageUtils;
import com.xinxin.websocket.utils.WebSocketUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author ：史鑫鑫
 * @date ：Created in 2019/4/27 20:12
 */

@Component
@ServerEndpoint("/chat/{username}")
public class ChatServer {

    @Autowired
    UserService service;


    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<ChatServer> servers = new CopyOnWriteArraySet<ChatServer>();
    private static CopyOnWriteArraySet<User> users = new CopyOnWriteArraySet<User>();

    /**
     * 通道建立成功需要执行的动作
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        System.out.println("连接已经建立，sessionID： " + session.getId());
        // 存储用户
        WebSocketUtils.USERS_ONLINE.put(username, session);
        Message msg = new Message(MessageUtils.createUUID(), username, new Date(), "enter", "用户【" + username + "】进入聊天室");
        System.out.println("发送消息：" + "用户【" + username + "】进入聊天室");
        WebSocketUtils.sendMessageToAllOnlineUser(MessageUtils.createMessage(msg));

        // 更新数据库
        System.out.println("更新数据库");
        WebSocketUtils.updateUser(username, "用户【" + username + "】进入聊天室");
        System.out.println("更新结束");

        // 转发人员信息
        sendPerson(username);
    }

    /**
     * 接受对方数据
     * @param message
     */
    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) {
        System.out.println("开始接受数据：" + message);
        Message msg = new Message(MessageUtils.createUUID(), username, new Date(), "text", message);
        WebSocketUtils.sendMessageToAllOnlineUser(MessageUtils.createMessage(msg));

        // 更新数据库
        System.out.println("更新数据库");
        WebSocketUtils.updateUser(username, message);
        System.out.println("更新结束");

        // 转发人员信息
        sendPerson(username);
    }

    /**
     * 关闭通道
     */
    @OnClose
    public void onClose(@PathParam("username") String username) {
        System.out.println("链接已经关闭");
        // 删除用户
        WebSocketUtils.USERS_ONLINE.remove(username);
        Message msg = new Message(MessageUtils.createUUID(), username, new Date(), "leave", "用户【" + username + "】离开聊天室");
        WebSocketUtils.sendMessageToAllOnlineUser(MessageUtils.createMessage(msg));

        // 更新数据库
        System.out.println("更新数据库");
        WebSocketUtils.updateUser(username, "用户【" + username + "】离开聊天室");
        System.out.println("更新结束");

        // 转发人员信息
        sendPerson(username);
    }

    /**
     * 错误处理
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 发送人员信息
     */
    public void sendPerson(String username) {
        Map map = new HashMap();
        map.put("users", WebSocketUtils.getAllOnlineUser());
        Message refreshmsg = new Message(MessageUtils.createUUID(), username, new Date(), "refresh", new Gson().toJson(map));
        WebSocketUtils.sendMessageToAllOnlineUser(MessageUtils.createMessage(refreshmsg));
    }
}
